package com.sunyard.authorization.service.impl;

import com.sunyard.authorization.service.TokenService;
import com.sunyard.constant.CommonConst;
import com.sunyard.response.Response;
import com.sunyard.dal.entity.Staff;
import com.sunyard.dal.mapper.PopedomMapper;
import com.sunyard.dal.mapper.StaffMapper;
import com.sunyard.redisUtil.RedisUtil;
import com.sunyard.utils.TimeUtil;
import com.sunyard.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class TokenServiceImpl implements TokenService {

    @Autowired
    private PopedomMapper popedomMapper;

    @Autowired
    private StaffMapper staffMapper;

    @Value("${login.redisExpireTime:30}")
    private Integer redisExpireTime;

    @Override
    public String fetchManageToken(String opId, String opName, String orgId, String roleId, String orgLevel, String auditType) {
        long currentTimeMillis = System.currentTimeMillis();
        String token = TokenUtil.sign(opId, opName, orgId, roleId, orgLevel, auditType, currentTimeMillis,redisExpireTime*30*1000);
        RedisUtil.set("login:operator:" + opName, currentTimeMillis, redisExpireTime*60);
        log.info("生成登录token:{}",token);
        return token;
    }

    @Override
    public String fetchMerchantToken(String loginName) {
        long currentTimeMillis = System.currentTimeMillis();
        String token = TokenUtil.signMerchant(loginName, currentTimeMillis,redisExpireTime*30*1000);
        RedisUtil.set("login:merchant:" + loginName, currentTimeMillis, redisExpireTime*60);
        Staff staff = staffMapper.selectByLoginName(loginName);
        String key = "popedom:loginStaff:" + staff.getStaffId();
        List popedomList = null;
        Object obj = RedisUtil.get(key);
        if (obj == null) {
            popedomList = popedomMapper.getMchntShiroList(String.valueOf(staff.getUserType()));
            RedisUtil.set(key, popedomList);
        }
        return token;
    }

    @Override
    public Object refreshToken(String token) {
        String account = TokenUtil.getOpId(token);
        Long currentTime = TokenUtil.getCurrentTime(token);
        String opName = TokenUtil.getOpName(token);
        String roleId = TokenUtil.getRoleId(token);
        String orgLevel = TokenUtil.getOrgLevel(token);
        String auditType = TokenUtil.getAuditType(token);
        String userPopedomKey = "popedom:loginOperator:" + roleId;
        String opNameKey = "login:operator:" + opName;
        log.info("当前登录人：{}，当前时间：     {}", opName, TimeUtil.millisToDateStr(System.currentTimeMillis()));
        log.info("当前登录人：{}，token里的时间：{}", opName, TimeUtil.millisToDateStr(currentTime));
        // 判断Redis中RefreshToken是否存在
        if (RedisUtil.hasKey(opNameKey)) {
            // Redis中RefreshToken还存在，获取RefreshToken的时间戳
            Long currentTimeMillisRedis = (Long) RedisUtil.get(opNameKey);
            log.info("当前登录人：{}，redis里的时间：{}", opName, TimeUtil.millisToDateStr(currentTimeMillisRedis));
            // 获取当前AccessToken中的时间戳，与RefreshToken的时间戳对比，如果当前时间戳一致，进行AccessToken刷新
            if (currentTimeMillisRedis.equals(currentTime)) {
                // 获取当前最新时间戳
                Long currentTimeMillis = System.currentTimeMillis();
                RedisUtil.set(opNameKey, currentTimeMillis,
                        redisExpireTime*60);
                RedisUtil.expire(userPopedomKey, redisExpireTime*60);
                log.info("刷新token 当前登录人：{}，新时间：{}", opName, TimeUtil.millisToDateStr(currentTimeMillis));
                // 刷新AccessToken，设置时间戳为当前最新时间戳
                token = TokenUtil.sign(account, TokenUtil.getOpName(token), TokenUtil.getOrgId(token), roleId, orgLevel, auditType, currentTimeMillis,redisExpireTime*30*1000);
                log.info("刷新完成");
                return Response.success(token);
            }
            return CommonConst.getResult(CommonConst.NOT_LOGIN, "token过期，请重新登录");
        }
        return CommonConst.getResult(CommonConst.NOT_LOGIN, "token过期，请重新登录");
    }

    public Object getPermision() {
        return null;
    }

}
